/**
 * @Author: SevDaisy十七散人 
 * @Date: 2020-07-05 16:29:00
 */
package zyy.ui;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import zyy.model.BeanMerchant;
import zyy.model.BeanOrderProjects;
import zyy.model.BeanProduct;
import zyy.model.BeanProduct_Dir;
import zyy.util.BaseException;
import zyy.util.Bus;
import zyy.util.BusinessException;

public class FrmUserGo extends JDialog implements ActionListener {
  private static final long serialVersionUID = -990815448731736703L;
  // 商家
  private BeanMerchant currentMerchant = null;
  private Object tblMerchantTitle[] = BeanMerchant.tableTitles;
  private Object tblMerchantData[][];
  DefaultTableModel tabMerchantModel = new DefaultTableModel();
  private JTable dataTableMerchant = new JTable(tabMerchantModel);
  List<BeanMerchant> allMerchant = null;
  // 商品目录
  private BeanProduct_Dir currentProduct_Dir = null;
  private Object tblProduct_DirTitle[] = BeanProduct_Dir.tableTitles;
  private Object tblProduct_DirData[][];
  DefaultTableModel tabProduct_DirModel = new DefaultTableModel();
  private JTable dataTableProduct_Dir = new JTable(tabProduct_DirModel);
  List<BeanProduct_Dir> allProduct_Dir = null;
  // 商品信息
  private BeanProduct currentProduct = null;
  private Object tblProductTitles[] = BeanProduct.tableTitles;
  private Object tblProductData[][];
  DefaultTableModel tabProductModel = new DefaultTableModel();
  private JTable dataTableProduct = new JTable(tabProductModel);
  List<BeanProduct> allProduct = null;
  // 订单的商品详情信息
  // private BeanOrderProjects currentOrderProjects = null;
  private Object tblOrderProjectsTitles[] = BeanOrderProjects.tableTitles;
  private Object tblOrderProjectsData[][];
  DefaultTableModel tabOrderProjectsModel = new DefaultTableModel();
  private JTable dataTableOrderProjects = new JTable(tabOrderProjectsModel);
  List<BeanOrderProjects> allOrderProjects = null;
  private int OrderDetailIndex;

  // Panel 布局
  private JPanel mdpTblPanel = new JPanel();
  private JPanel orderInfoTablePanel = new JPanel();
  private JPanel toolBarPanel = new JPanel();

  private JButton exit = new JButton("放弃订单");
  private JButton add = new JButton("购入");
  private JButton unadd = new JButton("减少");
  private JButton done = new JButton("结算");

  @Override
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == this.exit) {
      try {
        FrmUserGo.this.reloadOrderProjectsable();
        // System.out.println("OrderID is " + Link.currentOrder.getOrderID());
        System.out.println("InfoItem count is " + allOrderProjects.size());
        // if (allOrderProjects.size() != 0)
        Bus.orderManager.removeByOrderID(Bus.currentOrder.getOrderID());
        // System.exit(0);
        FrmUserGo.this.setVisible(false);
        // } catch (DbException e1) {
      } catch (Exception e1) {
        JOptionPane.showMessageDialog(null, "删除已创建的订单失败\n" + e1.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        e1.printStackTrace();
      }
    } else if (e.getSource() == this.add) {
      try {
        Bus.orderInfoManager.add_1(this.currentProduct);
        FrmUserGo.this.reloadOrderProjectsable();
        if (this.allOrderProjects.size() > this.OrderDetailIndex
            && this.allOrderProjects.get(this.OrderDetailIndex).getOpCnt() >= 1)
          this.dataTableOrderProjects.setRowSelectionInterval(this.OrderDetailIndex, this.OrderDetailIndex);
      } catch (BusinessException e1) {
        JOptionPane.showMessageDialog(null, "添加商品到订单失败\n" + e1.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        e1.printStackTrace();
      }
    } else if (e.getSource() == this.unadd) {
      try {
        Bus.orderInfoManager.unadd_1(this.currentProduct);
        FrmUserGo.this.reloadOrderProjectsable();
        if (this.allOrderProjects.size() > this.OrderDetailIndex
            && this.allOrderProjects.get(this.OrderDetailIndex).getOpCnt() >= 1)
          this.dataTableOrderProjects.setRowSelectionInterval(this.OrderDetailIndex, this.OrderDetailIndex);
      } catch (Exception e1) {
        JOptionPane.showMessageDialog(null, "从订单移除商品失败\n" + e1.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        e1.printStackTrace();
      }
    } else if (e.getSource() == this.done) {
      new FrmUserAddress();
      // FrmUserAddress FUserAddress = new FrmUserAddress();
      System.out.println("您的订单：" + Bus.currentOrder);
      // this.setVisible(false);
    }
  }

  public void reloadMerchantTable() {
    try {
      allMerchant = Bus.merchantManager.loadALL();
    } catch (BaseException e) {
      JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
      return;
    }
    tblMerchantData = new Object[allMerchant.size()][BeanMerchant.tableTitles.length];
    for (int i = 0; i < allMerchant.size(); i++) {
      for (int j = 0; j < BeanMerchant.tableTitles.length; j++)
        tblMerchantData[i][j] = allMerchant.get(i).getCell(j);
    }
    tabMerchantModel.setDataVector(tblMerchantData, tblMerchantTitle);
    this.dataTableMerchant.validate();
    this.dataTableMerchant.repaint();
  }

  public void reloadProduct_DirTable() {
    if (FrmUserGo.this.currentMerchant == null) {
      JOptionPane.showMessageDialog(null, "请选择一个商家", "错误", JOptionPane.ERROR_MESSAGE);
    }
    try {
      allProduct_Dir = Bus.Product_DirManager.loadByMID(FrmUserGo.this.currentMerchant.getMID());
    } catch (BaseException e) {
      JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
      return;
    }
    tblProduct_DirData = new Object[allProduct_Dir.size()][BeanProduct_Dir.tableTitles.length];
    for (int i = 0; i < allProduct_Dir.size(); i++) {
      for (int j = 0; j < BeanProduct_Dir.tableTitles.length; j++)
        tblProduct_DirData[i][j] = allProduct_Dir.get(i).getCell(j);
    }
    tabProduct_DirModel.setDataVector(tblProduct_DirData, tblProduct_DirTitle);
    this.dataTableProduct_Dir.validate();
    this.dataTableProduct_Dir.repaint();
  }

  public void reloadProductTable() {
    if (FrmUserGo.this.currentProduct_Dir == null) {
      JOptionPane.showMessageDialog(null, "请选择一个商品类别", "错误", JOptionPane.ERROR_MESSAGE);
    }
    try {
      allProduct = Bus.ProductManager.loadByProduct_DirID(FrmUserGo.this.currentProduct_Dir.getProductDirID());
    } catch (BaseException e) {
      JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
      return;
    }
    tblProductData = new Object[allProduct.size()][BeanProduct.tableTitles.length];
    for (int i = 0; i < allProduct.size(); i++) {
      for (int j = 0; j < BeanProduct.tableTitles.length; j++)
        tblProductData[i][j] = allProduct.get(i).getCell(j);
    }
    tabProductModel.setDataVector(tblProductData, tblProductTitles);
    this.dataTableProduct.validate();
    this.dataTableProduct.repaint();
  }

  public void reloadOrderProjectsable() {
    try {
      allOrderProjects = Bus.orderInfoManager.loadAll(Bus.currentOrder.getOrderID());
    } catch (BaseException e) {
      JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
      return;
    }
    tblOrderProjectsData = new Object[allOrderProjects.size()][BeanOrderProjects.tableTitles.length];
    for (int i = 0; i < allOrderProjects.size(); i++) {
      for (int j = 0; j < BeanOrderProjects.tableTitles.length; j++)
        tblOrderProjectsData[i][j] = allOrderProjects.get(i).getCell(j);
    }
    tabOrderProjectsModel.setDataVector(tblOrderProjectsData, tblOrderProjectsTitles);
    this.dataTableOrderProjects.validate();
    this.dataTableOrderProjects.repaint();
  }

  public FrmUserGo() {
    {
      Bus.fUserGo = this;
      this.setTitle("外卖助手 用户 点单界面");
      this.setSize(1318, 838);
      this.setLocationRelativeTo(null);
      // this.setDefaultCloseOperation(JDialog.EXIT_ON_CLOSE);
      this.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
          // 这里可以加一个确认(Yes/No)的JoptionPane，来设置关闭窗口是否要删除订单。但是我懒
          try {
            Bus.orderManager.removeByOrderID(Bus.currentOrder.getOrderID());
          } catch (Exception e1) {
            e1.printStackTrace();
            JOptionPane.showMessageDialog(null, "删除已创建的订单失败" + e1.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
          }

          System.exit(0);
        }
      });
      this.setVisible(true);
    }
    {
      // body 布局
      mdpTblPanel.setLayout(new BorderLayout());// 如果这里不设置的话，商品信息表将无法展示
      this.getContentPane().add(this.mdpTblPanel, BorderLayout.NORTH);
      this.getContentPane().add(this.orderInfoTablePanel, BorderLayout.CENTER);
      this.getContentPane().add(this.toolBarPanel, BorderLayout.SOUTH);
    }
    {
      // toolBarPanel 设置
      toolBarPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
      toolBarPanel.add(this.exit);
      toolBarPanel.add(this.add);
      toolBarPanel.add(this.unadd);
      toolBarPanel.add(this.done);
      Bus.jButtonZYYStyle(this.exit);
      Bus.jButtonZYYStyle(this.add);
      Bus.jButtonZYYStyle(this.unadd);
      Bus.jButtonZYYStyle(this.done);
      this.exit.addActionListener(this);
      this.add.addActionListener(this);
      this.unadd.addActionListener(this);
      this.done.addActionListener(this);
    }
    {
      // 商家信息表
      this.mdpTblPanel.add(new JScrollPane(this.dataTableMerchant), BorderLayout.WEST);
      this.dataTableMerchant.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent e) {
          int i = FrmUserGo.this.dataTableMerchant.getSelectedRow();
          if (i < 0) {
            return;
          }
          {
            // add for 商品分类
            FrmUserGo.this.currentMerchant = FrmUserGo.this.allMerchant.get(i);
            FrmUserGo.this.reloadProduct_DirTable();
            // 每次刷新都顺便增加默认选择
            FrmUserGo.this.currentProduct_Dir = FrmUserGo.this.allProduct_Dir.get(0);
            FrmUserGo.this.reloadProductTable();
            FrmUserGo.this.currentProduct = FrmUserGo.this.allProduct.get(0);
          }
          {
            // Debug OK
            System.out.println("allMerchant.size is " + FrmUserGo.this.allMerchant.size());
            System.out.println(FrmUserGo.this.currentMerchant);
          }
        }
      });
    }
    {
      // 商品分类表
      this.mdpTblPanel.add(new JScrollPane(this.dataTableProduct_Dir), BorderLayout.CENTER);
      this.dataTableProduct_Dir.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
          int i = FrmUserGo.this.dataTableProduct_Dir.getSelectedRow();
          if (i < 0) {
            return;
          }
          {
            // add for 商品信息
            FrmUserGo.this.currentProduct_Dir = FrmUserGo.this.allProduct_Dir.get(i);
            FrmUserGo.this.reloadProductTable();
          }
          {
            // OK
            System.out.println(FrmUserGo.this.currentProduct_Dir);
            System.out.println("allProduct_Dir.size is " + FrmUserGo.this.allProduct_Dir.size());
          }
        }
      });
    }
    {
      // 商品信息表
      this.mdpTblPanel.add(new JScrollPane(this.dataTableProduct), BorderLayout.EAST);
      this.dataTableProduct.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
          int i = FrmUserGo.this.dataTableProduct.getSelectedRow();
          if (i < 0) {
            return;
          }
          FrmUserGo.this.currentProduct = FrmUserGo.this.allProduct.get(i);
          System.out.println(FrmUserGo.this.currentProduct); // OK
        }
      });
    }
    {
      // 订单 商品详情表
      orderInfoTablePanel.setLayout(new BorderLayout());
      this.orderInfoTablePanel.add(new JScrollPane(this.dataTableOrderProjects), BorderLayout.CENTER);
      this.dataTableOrderProjects.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
          int i = FrmUserGo.this.dataTableOrderProjects.getSelectedRow();
          if (i < 0)
            return;
          FrmUserGo.this.OrderDetailIndex = i;
          BeanOrderProjects x = FrmUserGo.this.allOrderProjects.get(i);
          System.out.printf("从购物车更新当前商品 i: %d \t ProductID: %d \t opCnt: %.1f\n", i, x.getProductID(), x.getOpCnt());
          if (x.getOpCnt() > 0) {
            FrmUserGo.this.currentProduct.setProductID(x.getProductID());
            FrmUserGo.this.currentProduct.setpRealValue(x.getOpSum() / x.getOpCnt());
          }
        }
      });
      dataTableOrderProjects.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    }
    {
      // 初始化选择
      this.reloadMerchantTable();
      this.currentMerchant = FrmUserGo.this.allMerchant.get(0);
      this.reloadProduct_DirTable();
      this.currentProduct_Dir = FrmUserGo.this.allProduct_Dir.get(0);
      this.reloadProductTable();
      this.currentProduct = FrmUserGo.this.allProduct.get(0);
      this.reloadOrderProjectsable();
    }
  }
}